<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Reading, Download, Search, Refresh } from '@element-plus/icons-vue'
import { 
  createPropertyFee, 
  getAllPropertyFees, 
  getUnpaidResidents,
  createAllPropertyFees 
} from '@/api/adminApi'

// 数据状态
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const activeTab = ref('property')
const collectDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentBill = ref({})
const selectedBills = ref([])
const propertyList = ref([])

// 批量账单对话框
const batchBillDialogVisible = ref(false)
const batchBillForm = ref({
  periodStart: new Date().getFullYear(),
  periodEnd: new Date().getFullYear() + 1,
  amount: 600,
  dueDate: `${new Date().getFullYear()}-12-31`,
  status: '未支付'
})

// 统计数据
const stats = computed(() => {
  const totalAmount = propertyList.value.reduce((sum, item) => sum + item.amount, 0)
  const paidAmount = propertyList.value
    .filter(item => item.status === '已支付')
    .reduce((sum, item) => sum + item.amount, 0)
  const unpaidAmount = totalAmount - paidAmount
  const paidRate = totalAmount ? ((paidAmount / totalAmount) * 100).toFixed(1) : '0.0'

  return [
    { label: '本月应收', value: `¥${totalAmount.toFixed(2)}`, class: 'primary' },
    { label: '本月已收', value: `¥${paidAmount.toFixed(2)}`, class: 'success' },
    { label: '本月欠费', value: `¥${unpaidAmount.toFixed(2)}`, class: 'warning' },
    { label: '收缴率', value: `${paidRate}%`, class: 'info' }
  ]
})

// 账单管理对话框
const billManageVisible = ref(false)
const billForm = ref({
  userId: '',
  periodStart: new Date().getFullYear(),
  periodEnd: new Date().getFullYear() + 1,
  amount: 1000,
  status: '未支付',
  dueDate: ''
})

// 获取物业费列表
const fetchPropertyFees = async () => {
  loading.value = true
  try {
    const res = await getAllPropertyFees()
    if (res.code === 200) {
      propertyList.value = res.data
      total.value = res.data.length
    }
  } catch (error) {
    console.error('获取物业费列表失败:', error)
    ElMessage.error('获取物业费列表失败')
  } finally {
    loading.value = false
  }
}

// 获取未缴费居民
const fetchUnpaidResidents = async () => {
  try {
    const res = await getUnpaidResidents()
    if (res.code === 200) {
      return res.data
    }
  } catch (error) {
    console.error('获取未缴费居民失败:', error)
    ElMessage.error('获取未缴费居民失败')
  }
  return []
}

// 生成新账单
const createNewBill = async (formData) => {
  try {
    const res = await createPropertyFee(formData)
    if (res.code === 200) {
      ElMessage.success('账单生成成功')
      await fetchPropertyFees()
      return true
    }
  } catch (error) {
    console.error('生成账单失败:', error)
    ElMessage.error('生成账单失败')
  }
  return false
}

// 打开账单管理
const openBillManage = () => {
  billForm.value = {
    userId: '',
    periodStart: new Date().getFullYear(),
    periodEnd: new Date().getFullYear() + 1,
    amount: 1000,
    status: '未支付',
    dueDate: new Date().toISOString().split('T')[0]
  }
  billManageVisible.value = true
}

// 打开批量账单管理
const openBatchBillManage = () => {
  batchBillForm.value = {
    periodStart: new Date().getFullYear(),
    periodEnd: new Date().getFullYear() + 1,
    amount: 600,
    dueDate: new Date().toISOString().split('T')[0],
    status: '未支付'
  }
  batchBillDialogVisible.value = true
}

// 提交账单
const handleBillSubmit = async () => {
  try {
    if (await createNewBill(billForm.value)) {
      billManageVisible.value = false
    }
  } catch (error) {
    ElMessage.error('提交失败')
  }
}

// 提交批量账单
const handleBatchBillSubmit = async () => {
  try {
    const res = await createAllPropertyFees(batchBillForm.value)
    if (res.code === 200) {
      ElMessage.success('批量创建账单成功')
      batchBillDialogVisible.value = false
      await fetchPropertyFees()
    } else {
      ElMessage.error(res.message || '批量创建账单失败')
    }
  } catch (error) {
    console.error('批量创建账单失败:', error)
    ElMessage.error('批量创建账单失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    '已支付': 'success',
    '未支付': 'warning'
  }
  return types[status] || 'info'
}

// 计算属性：过滤后的列表
const filteredPropertyList = computed(() => {
  let result = propertyList.value
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item => 
      String(item.userId).includes(keyword) ||
      String(item.feeId).includes(keyword)
    )
  }
  
  // 分页处理
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  
  return result.slice(startIndex, endIndex)
})

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 初始化
onMounted(() => {
  fetchPropertyFees()
})
</script>

<template>
  <div class="admin-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" v-for="stat in stats" :key="stat.label">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value" :class="stat.class">{{ stat.value }}</div>
          <div class="stat-label">{{ stat.label }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="left">
        <el-button-group>
          <el-button type="primary" @click="openBillManage">
            <el-icon><Document /></el-icon>生成单个账单
          </el-button>
          <el-button type="success" @click="openBatchBillManage">
            <el-icon><Document /></el-icon>批量生成账单
          </el-button>
          <el-button type="warning" @click="fetchPropertyFees">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </el-button-group>
      </div>
      <div class="right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户ID/账单ID"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 费用列表 -->
    <el-table
      :data="filteredPropertyList"
      border
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column prop="feeId" label="账单ID" width="80" />
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column label="收费周期" width="200">
        <template #default="{ row }">
          {{ row.periodStart }} - {{ row.periodEnd }}
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="金额" width="120">
        <template #default="{ row }">
          <span class="amount">¥{{ row.amount.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="dueDate" label="截止日期" width="180">
        <template #default="{ row }">
          {{ formatDate(row.dueDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="paidAt" label="支付时间" width="180">
        <template #default="{ row }">
          {{ row.paidAt ? formatDate(row.paidAt) : '未支付' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 生成单个账单对话框 -->
    <el-dialog
      v-model="billManageVisible"
      title="生成新账单"
      width="500px"
    >
      <el-form :model="billForm" label-width="100px">
        <el-form-item label="用户ID" required>
          <el-input v-model="billForm.userId" type="number" />
        </el-form-item>
        <el-form-item label="收费年度" required>
          <el-col :span="11">
            <el-input-number v-model="billForm.periodStart" :min="2000" :max="2100" />
          </el-col>
          <el-col :span="2" class="text-center">-</el-col>
          <el-col :span="11">
            <el-input-number v-model="billForm.periodEnd" :min="2000" :max="2100" />
          </el-col>
        </el-form-item>
        <el-form-item label="金额" required>
          <el-input-number v-model="billForm.amount" :precision="2" :step="100" :min="0" />
        </el-form-item>
        <el-form-item label="截止日期" required>
          <el-date-picker
            v-model="billForm.dueDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="billManageVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBillSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量生成账单对话框 -->
    <el-dialog
      v-model="batchBillDialogVisible"
      title="批量生成账单"
      width="500px"
    >
      <el-form :model="batchBillForm" label-width="100px">
        <el-form-item label="收费年度" required>
          <el-col :span="11">
            <el-input-number v-model="batchBillForm.periodStart" :min="2000" :max="2100" />
          </el-col>
          <el-col :span="2" class="text-center">-</el-col>
          <el-col :span="11">
            <el-input-number v-model="batchBillForm.periodEnd" :min="2000" :max="2100" />
          </el-col>
        </el-form-item>
        <el-form-item label="金额" required>
          <el-input-number v-model="batchBillForm.amount" :precision="2" :step="100" :min="0" />
        </el-form-item>
        <el-form-item label="截止日期" required>
          <el-date-picker
            v-model="batchBillForm.dueDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchBillDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchBillSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.admin-container {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-value.primary { color: #409EFF; }
.stat-value.success { color: #67C23A; }
.stat-value.warning { color: #E6A23C; }
.stat-value.info { color: #909399; }

.stat-label {
  color: #606266;
  font-size: 14px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 250px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.text-center {
  text-align: center;
  line-height: 32px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    gap: 10px;
  }

  .search-input {
    width: 100%;
  }
}
</style>